#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <time.h>

#include "Task.hpp"
#include "RingQueue.hpp"
#include "Task.hpp"

struct ThreadData
{
    RingQueue<Task> *rq;
    std::string threadname;
};

void *Comsumer(void *args) // 消费者
{
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->threadname;
    while (true)
    {
        // 消费数据
        Task t;
        rq->Pop(&t);
        // 处理数据
        t.Run();
        std::cout << "Cosumer task done,is: " << t.GetTask() << ",result: " << t.Getresult() << std::endl;
        sleep(1);
    }
    return nullptr;
}

void *Productor(void *args) // 生产者
{
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->threadname;
    int len = opers.size();
    while (true)
    {
        // 弄随机数
        int data1 = rand() % 10 + 1;
        usleep(10000);
        int data2 = rand() % 10;
        char op = opers[rand() % len];
        Task t(data1, data2, op);

        // 生产数据
        rq->Push(t);
        std::cout << "Proctor task done,is: " << t.GetTask() << "who: " << name << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr));
    RingQueue<Task> *rq = new RingQueue<Task>();

    pthread_t c[5], p[3];
    for (int i = 0; i < 5; i++)
    {
        ThreadData*td=new ThreadData();
        td->rq=rq;
        td->threadname="Cosumer-"+std::to_string(i);
        pthread_create(c+i, nullptr, Comsumer, td);
    }
    for (int i = 0; i < 3; i++)
    {
        ThreadData*td=new ThreadData();
        td->rq=rq;
        td->threadname="Produuctor-"+std::to_string(i);
        pthread_create(p+i, nullptr, Productor, td);
    }

    for(int i=0;i<5;i++)
    {
    pthread_join(c[i], nullptr);
    
    }
    for(int i=0;i<3;i++)
    {
        pthread_join(p[i], nullptr);
    }
    delete rq;
    return 0;
}